package com.game.majiang.logic;

import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

import com.game.majiang.Event.Time.TimeEvent;
import com.game.majiang.Event.Time.TimeListener;
import com.game.majiang.Event.Time.TimeManager;
import com.game.majiang.config.DataManager;
import com.game.majiang.config.LogManager;
import com.game.majiang.logic.chexuan.ChexuanRoom;
import com.game.majiang.vo.ParameterVo;
import com.game.majiang.vo.ProxyVo;
import com.game.majiang.vo.RoomConfigVo;
import com.game.majiang.vo.UserVo;
import com.game.server.GameServer;
import com.game.server.db.dao.UsersDao;
import com.game.server.db.dao.XyClubInfoDao;
import com.game.server.db.dao.XyClubMemberInfoDao;
import com.game.server.db.dao.XyUnionInfoDao;
import com.game.server.db.entity.XyClubInfo;
import com.game.server.db.entity.XyClubMemberInfo;
import com.game.server.db.entity.XyUnionInfo;
import com.game.server.system.AbstractClient;
import com.game.server.system.AbstractServer;
import com.game.server.util.Util;
import com.robot.RobotManager;
import com.timing.RobotTask;

public class LogicServer extends AbstractServer implements TimeListener {
    static LogicServer instance;
    public TimeManager m_TimeManager;
    public boolean startBool = false;
    protected TimerTask dingshitask = null;
    protected Timer dingshitimer = null;
    proxytimer my_proxytimer;

    public LogicServer(short id) {
        super(id);
        m_TimeManager = new TimeManager();
        m_TimeManager.addTimeListener(this);
    }

    public static LogicServer getInstance() {
        if (instance == null) {
            instance = new LogicServer((short) 1);
        }
        return instance;
    }

    public static int[] IntegerConvertint(Integer[] temp) {
        int[] ints = new int[temp.length];
        for (int i = 0; i < temp.length; i++) {
            ints[i] = temp[i].intValue();
        }
        return ints;
    }

    /**
     * 查询代理的 小目标
     */
    public void proxy_01() {

        List<ProxyVo> proxys = ProxyVo.getProxy();
        //		int systemValue =Integer.parseInt(DataManager.getInstance().systemValue("xiaomubiao")) ;
        int systemValue = 3000;
        Date date = new Date();

        for (ProxyVo proxy : proxys) {

            Calendar c = Calendar.getInstance();
            c.setTime(proxy.getQishishijian());
            c.add(Calendar.MONTH, 1);
            double sqlAddSum = ProxyVo.sqlAddSum(proxy.getId(), proxy.getQishishijian() + "", c.getTime() + "");

            BigDecimal bd = new BigDecimal(proxy.getIntegral()).setScale(0, BigDecimal.ROUND_HALF_UP);
            int goid = Integer.parseInt(bd.toString());

            if (date.getTime() >= c.getTimeInMillis()) {
                LogicServer server = LogicServer.getInstance();
                Collection<AbstractClient> c1 = server.getClients();
                ProxyVo.updateProxy(proxy.getId(), "status", 0);
                boolean falg = true;
                for (AbstractClient ab : c1) {
                    if (ab.getUserId() == proxy.getUid()) {
                        falg = false;
                    }
                }
                LogicClient client = (LogicClient) server.getClient(proxy.getUid());
                if (proxy.getIsqianfei() == 0) {
                    //					mai.setContent(DataManager.getInstance().systemValue("proxyyoujian03")+"推广员返利积分返回:"+proxy.getIntegral());

                    if (!falg) {

                        LogManager.getInstance().Log("用户id为:" + proxy.getUid() + "的用户充值:" + goid + "币");

                        client.getVo().AddIntegral(goid);


                        client.getVo().Savenomajin();
                        //			UserVo.updateGlod(uid, gold);
                    } else {

                        UserVo.updateGlod(proxy.getUid(), goid, 3);
                        int cc = UserVo.getGlodm(proxy.getUid(), 3);
                        if (cc < 0) {

                            UserVo.updateGlod(proxy.getUid(), Math.abs(cc), 3);
                            LogManager.getInstance().Log("用户id为:" + proxy.getUid() + "的用户充值:" + goid + "币之后为负：" + cc);
                        }

                        LogManager.getInstance().Log("用户id为:" + proxy.getUid() + "的用户充值:" + goid + "币");
                    }


                } else if (sqlAddSum >= systemValue) {
                    //					mai.setContent("proxyyoujian02"+DataManager.getInstance().systemValue("proxyyoujian02"));
                } else {
                    ProxyVo.updateProxy(proxy.getId(), "status", 0);
                    //					mai.setContent(DataManager.getInstance().systemValue("proxyyoujian01"));
                }

                ProxyVo.updateProxy(proxy.getId(), "isqianfei", 0);
                ProxyVo.updateProxy2(proxy.getId());
               

            }


        }


    }

   
    /**
     * 用户登录
     *
     * @param client
     * @return
     */
    public boolean login(LogicClient client) {
        LogicClient old = (LogicClient) this.getClient(client.getUserId());
//        		if(client.getUserId()>10000)
//        		{
//
//
//        			TaskVo.expiryOfTheTask(client,true);
//        		}


        if (old != null && old.getTable() != null && old.getRoom() != null) {
//            UserInfo rsp = new UserInfo();
            UserVo.getuserinfo(client);

        }
        if (this.addClient(client)) {
        	  UserVo.getuserinfo(client);

            return true;
        } else {
            return false;
        }
    }

    /**
     * 服务器初始化
     */
    public void init() {

        LogManager.getInstance().Log("服务器初始化开始");
        DataManager.getInstance().setSys_parameter(ParameterVo.getList());
        DataManager.getInstance().setSys_parameterServerType(ParameterVo.getListParameterServerType());

        DataManager.getInstance().setRoommap(RoomConfigVo.getRoomConfigVo());
        UsersDao.updateIntegral();

//		初始化用户基础数据 begin---------------
        DataManager.getInstance().setMapUserData(UsersDao.selectAllUserData());
//		初始化用户基础数据 end---------------

        LogManager.getInstance().Log("服务器初始化开始33333");
//		初始化俱乐部数据 begin---------------
        DataManager.getInstance().setMapClub(XyClubInfoDao.selectAll());//俱乐部 写入缓存
        DataManager.getInstance().setMapUnion(XyUnionInfoDao.selectAll());//联盟写入缓存
        HashMap<Integer, XyClubInfo> mapClub = DataManager.getInstance().getMapClub();
        HashMap<Integer, XyUnionInfo> mapUnion = DataManager.getInstance().getMapUnion();
        List<XyClubMemberInfo> xyClubMemberInfos = XyClubMemberInfoDao.selectAll();

        for (Map.Entry<Integer,XyClubInfo> clubInfoEntry : mapClub.entrySet()) {
            for (XyClubMemberInfo entity : xyClubMemberInfos) {
                if (clubInfoEntry.getValue().getId() == entity.getCid()){
                    //将俱乐部用户添加到俱乐部实体中
                    clubInfoEntry.getValue().addPlayer(entity);
                    //将俱乐部ID添加到用户基础数据中
                    if (entity.getDel_type()==0){
                        DataManager.getInstance().getMapUserData().get(entity.getUid()).getClubids().add(clubInfoEntry.getValue().getId());
                    }
                }
            }
            if (clubInfoEntry.getValue().getUnionid()!=0){
                XyUnionInfo xyUnionInfo = mapUnion.get(clubInfoEntry.getValue().getUnionid());
                if (xyUnionInfo!=null){
                    String join = String.join(",", xyUnionInfo.getClubids().stream().map(String::valueOf).collect(Collectors.toList()));
                    String[] strs = join.split(",");
                    if (!Util.useSetArr(strs,clubInfoEntry.getValue().getId()+"")) {
                        xyUnionInfo.getClubids().add(Integer.valueOf(clubInfoEntry.getValue().getId()));
                    }
                }
            }
        }


        HashMap<Integer, RoomConfigVo> temproommap = DataManager.getInstance().getRoommap();
        Iterator iter = temproommap.entrySet().iterator();
        LogManager.getInstance().Log("房间初始化iter:"+ iter.toString());
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Integer key = (Integer) entry.getKey();
            RoomConfigVo val = (RoomConfigVo) entry.getValue();
            LogManager.getInstance().Log("房间初始化key:"+key);
            if (key == 1) {
            	ChexuanRoom room = new ChexuanRoom(val);
            	this.addRoom(room);
            }
        }
    }

  
    /**
     * 服务器关闭
     *
     * @return
     */
    public boolean close() {
        DataManager.getInstance().setSys_parameter(null);
//		DataManager.getInstance().setTaskStructure(null);
//		DataManager.getInstance().setAccept(null);
//		DataManager.getInstance().setComplete(null);
//		DataManager.getInstance().setMatch(null);
//		DataManager.getInstance().setPracticegame(null);
        DataManager.getInstance().setRoommap(null);
        HashMap<Integer, RoomConfigVo> temproommap = null;
        Iterator iter = null;
        GameServer game = new GameServer();
        game.getInstance().setRunning(false);
        return true;

    }

    // �������
    public void Cmd(String[] cmds) {
        String cmd = cmds[0].toLowerCase();

        if (cmd.equals("openlog")) {
            LogManager.getInstance().isopen = true;
        } else if (cmd.equals("stoplog")) {
            LogManager.getInstance().isopen = false;
        } 
    }

    public byte CloseRebot(int uid) {
        byte ret = 0; //�ɹ�
        AbstractClient c = this.getClient(uid);
        if (c != null) {
            c.Close();
        } else {
            ret = 1; //��Ҳ�����
        }
        return ret;
    }

 



   

    //	class chuxianTimer extends TimerTask{
    //		@Override
    //		public void run() {
    ////			this.cancel();
    ////			fuwutask=null;
    ////			LogManager.getInstance().Log("--------------当前开始关闭虚拟房间！！！");
    ////			for (AbstractRoom room : LogicServer.getInstance().getRooms()) {
    ////				for (AbstractTable ta : room.getTables()) {
    ////					if(ta.ifxujia) {
    ////						chexuantable table = (chexuantable)ta;
    ////						table.xunitiren();
    ////					}
    ////				}
    ////			}
    ////			LogManager.getInstance().Log("--------------当前已经关闭虚拟房间，已经开始新的虚拟房间循环！！！");
    ////			xunitable00();
    ////
    //		}
    //	}

    @Override
    public void timeEvent(TimeEvent event) {
        if (startBool) {

        }

    }

    
    class proxytimer extends TimerTask {
        public void run() {

            proxy_01();
        }
    }

}
